var service = new EbeimService();
var onceKey = true;
var pathNodes = [];
var pathSet = {
		async: {
            enable: true,
            url: "/rest/system/dirs",
            autoParam: ["path"],
            dataType: "json",
            dataFilter:function(treeId, parentNode, responseData){
            	var nodes = [];
                getPathTree(responseData,nodes);
                return nodes;
            	
            },
            type:"get"
        },
        view: {
            fontCss: getFont,
            dblClickExpand: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: pathClick
        }
    };

var getUserInfoCB = function(data){
	if(data.user.labType!="1"&&data.user.labType!="3"){
		$("#dsNeedKey").attr("disabled","disabled");
	}
}

$(window).load(function(){
	service.getUserInfo({},getUserInfoCB);
});

function changeTitle(){
	var title=$('title').text();
	$("title").text(title+"|titleCount");
}

var callback = function(data) {
	$("#save").removeAttr("disabled");
	var json = data;
	if (json.code == 200 || json.code == "200") {
		plugin.msgtip({type: "o", msg: "保存成功！"});
		setTimeout(function(){
			historyGo();
		}, 1000);
		changeTitle();
	} else {
		dsSecurityRankCheck(json,json.message);
	}
};

function historyGo(){
	var dsType = getParameter("dsType");
	if(dsType=="0"){
//		window.location.href = "/static/html/client-list.html?dsType=0&timestamp="+new Date().getTime();
		window.location.href = "/static/upload.html";
	}else if(dsType=="2"){
//		window.location.href = "/static/html/client-safeBox.html?timestamp="+new Date().getTime();
		window.location.href = "/static/upload.html";
	}else{
//		window.history.go(-1);
	}
}

function setDynamicCode() {
	var dynamicCode = $("#dynamicCode").val().replace(/(^\s+)|(\s+$)/g,"");
	if (dynamicCode == "") {
		plugin.msgtip({type: "e", msg: "动态验证码不能为空!"});
		return;
	}
	saveDataSource(dynamicCode);
}

var saveDataSource = function(dynamicCode) {
	var dsType = $('#dsType').val();
	if (dsType == "0") {
		if ($('#dsPath').val() == "") {
			plugin.msgtip({type: "e", msg: "请选择路径"});
			return;
		}
	}
	var isOpenLocalBackup = 0;
	if ($('#isOpenLocalBackup')[0].checked) {
		isOpenLocalBackup = 1;
	}
	
	var dsNeedKey = 0;
	var dsNeedKeyCked = $("#dsNeedKey")[0].checked;
	if(dsNeedKeyCked){
		dsNeedKey = 1;
	}
	var dsNeedCode = 0;
	var dsNeedCodeCked = $("#dsNeedCode")[0].checked;
	if(dsNeedCodeCked){
		dsNeedCode = 1;
	}
	var dsSecurityRank = 0;
	if(dsNeedKey==1 && dsNeedCode==0){
		dsSecurityRank = 1;
	}else if(dsNeedKey==0 && dsNeedCode==1){
		dsSecurityRank = 2;
	}else if(dsNeedKey==1 && dsNeedCode==1){
		dsSecurityRank = 3;
	}
	
	var root = $('#dsPath').val();
	var s_path = root;
	
	var name = s_path;
	var idx = s_path.lastIndexOf("\\");
	if(idx == s_path.length-1){
		s_path = s_path.substring(0,idx);
	}
	idx = s_path.lastIndexOf("\\");
	if(idx != -1){
		name = s_path.substring(idx+1,s_path.length);
	}
	if (dsType == "1") {
		name = $("#dbName").val();
		var query = 0;
		$(".query").each(function(){
			if($(this).val()==""){
				query++;
			}
		});
		if(query>0){
			plugin.msgtip({type: "e", msg: "请配置数据库信息"});
			return;
		}
	}
	var ds = {
		id : $("#h_dsId").val(),
		name : name,
		description : $('#description').val(),
		dsType : $('#dsType').val(),
		isOpenLocalBackup : isOpenLocalBackup,
		dsSecurityRank : dsSecurityRank,
		dynamicCode : dynamicCode
	};
	var time = $('#datetimepicker').val();
	var stamp = getTimeStamp(time);
	var period = $("#period").val();
	var reg = /^[0-9]*[1-9][0-9]*$/.test(period); //正整数
	if(!reg){
		plugin.msgtip({type: "e", msg: "时间间隔请输入正整数！"});
		return;
	}
	if(period > 48 || period < 1){
		plugin.msgtip({type: "e", msg: "请输入1~48之间的数字！"});
		return;
	}
	var type = 1;
	if($('#dsType').val()=="2"){
		type=2;
	}
	
	var bs = {
		type : type,
		backupTime : stamp,
		backupCycle : period,
		backupPeriod : $("#unit").val(),
	}
	var isEncrypt = 0;
	var isEncryptCked = $("#isEncrypt")[0].checked;
	if(isEncryptCked){
		isEncrypt = 1;
	}
	var config = {
		isEncrypt:isEncrypt,
		root : root,
		dbUsername : $("#dbUsername").val(),
		dbPassword : $("#dbPassword").val(),
		dbHost : $("#dbHost").val(),
		dbType : $("#dbType").val(),
		dbPort : $("#dbPort").val(),
		dbName : $("#dbName").val()
	}
//	json["datasource"] = ds;
//	json["datasourceConfig"] = config;
//	json["backStrategy"] = bs;
//	json["root"] = $('#dsPath').val();
//	$("#save").attr("disabled","disabeld");
//	service.addDataSource(json, callback);
	 $.ajax({
         url: "/api/datasources/save?path=" + root ,
         dataType: 'json',
         type: "POST",
         cache: false,
         success: function(data) {
             window.location.href = "/static/upload.html"
         }.bind(this),
         error: function(xhr, status, err) {
           console.error(status, err.toString());
         }.bind(this)
     });
};

var getCheckedValue = function(chk) {
	if (chk.prop("checked")) {
		return 1;
	}
	return 0;
};

function confirmDsDir(){
	var abDir = $("#ab-ds-dir").val();
	if(abDir==""){
		plugin.msgtip({type: "e", msg: "请选择目录"});
		return;
	}
	$("#h_ds_path").val(abDir);
	$("#ab-ds-dir").val("");
	$(".window").css("display","none");
	onceKey = true;
	var ls = abDir.substring(abDir.length,abDir.length-1);
	if(ls == "/"){
		abDir = abDir.substring(0,abDir.length-1);
	}
	var h_which_path = $("#h_which_path").val();
	if(h_which_path == "dsPath"){
		$("#dsPath").val(abDir);
	}
	
}
function cancelDsDir(){
	$("#ab-ds-dir").val("");
	$(".window").css("display","none");
	onceKey = true;
}

function selectDsPath(path,whichPath){
	
	if(whichPath){
		$("#h_which_path").val(whichPath);
	}
	
	var $W = $(window).width();
	var $H = $(window).height();
	var w = $(".window").width(); 
	var h = $(".window").height();
	$(".window").css("top",(($H-h)/2)-80);
	$(".window").css("left",($W-w)/2);
	$("#dsWindow").css("display","block");
	while(path.charAt(path.length - 1) == "\\" && path.charAt(path.length - 2) != ":"){
		path = path.substring(0,path.length-1)
	}
	$("#ab-ds-dir").val(path);
	service.getSystemDirs(
		{
			path:path
		}, 
		selectDsPathCB
	);
}
function selectDsParentPath(path){
	var abDir = $("#ab-ds-dir").val();
	var idx = abDir.lastIndexOf("\\");
	if(abDir.charAt(abDir.length - 2) != ":" && idx!=-1){
		abDir = abDir.substring(0,idx);
		if(abDir.charAt(abDir.length - 1) == ":"){
			abDir = abDir+"\\";
		}
		$("#ab-ds-dir").val(abDir);
    	service.getSystemDirs(
    			{
    				path:abDir
    			},
    			selectDsPathCB
    		);
	}else{
		$("#ab-ds-dir").val("");
		service.getSystemDirs(
				{
					path:""
				},
				selectDsPathCB
			);
	}
}
var selectDsPathCB = function(data){
	if(data.code == "500"){
		plugin.msgtip({type: "e", msg: "系统找不到该路径！"});
		return false
	}
	var json = data;
	var content = "";
	if(onceKey == true){
		onceKey = false;
		getPathTree(data,pathNodes);
		$.fn.zTree.init($("#pathTree"), pathSet, pathNodes);
	}
	for (var i = 0; i < json.length; i++) {
		var name = json[i].name;
		
		var showName = name;
		if(showName.indexOf("\Desktop")!=-1){
			showName = "桌面"
				name = name.split("\\").join("\\\\");
		}
		var clazz = "j-file";
		if(json[i].isParent){
			clazz = "j-path";
		}
		content = content +
		"<li class='"+clazz+"' title='"+name+"' data-path='"+json[i].absolutePath+"'><a href='javascript:;'><p>"+showName+"</p></a></li>";
	}
	$(".w-dir-list ul").html(content);
}

$(function(){
	var dsType = getParameter("dsType");
	$("#dsType").val(dsType);
	$("#datetimepicker").val(getTimeStr(new Date().getTime()));
	if(dsType=="0"){
		$("#dbDiv").css("display","none");
	}else if(dsType=="1"){
		$("#folderDiv").css("display","none");
	}else if(dsType=="2"){
		$("#bsDiv").css("display","none");
		$("#dbDiv").css("display","none");
	}else{
		plugin.msgtip({type: "o", msg: "参数缺失！"});
//		window.history.go(-1);
	}
	
	var dsId = getParameter("dsId");
	if(dsId != undefined && dsId != ""){
		$("#h_dsId").val(dsId);
		service.getDataSource(dsId,dsCB);
	}
	
	$(".lab-check").hover(function(){
		var t = $(this);
		if(t.siblings("input[type='checkbox']").attr("disabled") == "disabled"){
			t.css("cursor","not-allowed");
		}
		return false;
	});
	
	$("#ab-ds-dir").keydown(function(){
		if (event.keyCode == 13) { 
			var val = $(this).val();
			val = val.replace(/\//g, "\\");
			if(val.charAt(val.length - 1) == ":"){
				val = val+"\\";
			}
			$(this).val(val);
			selectDsPath(val);
		}
	})
	
	$(".w-dir-list").delegate(".j-path","click",function(){
		var val = $(this).attr("data-path");
		selectDsPath(val);
	})
	
	$(".w-dir-list").delegate(".j-file","click",function(){
		var val = $(this).attr("data-path");
		selectFilePath(val);
	})
	

	$(".lab-check").bind("click",function(){
		var t = $(this);
		if(t.siblings("input[type='checkbox']").attr("disabled") == "disabled"){
			return false;
		}
		if(t.hasClass("check-true")){
			t.removeClass("check-true");
			t.siblings("input[type='checkbox']").prop("checked", false);
		}else{
			t.addClass("check-true");
			t.siblings("input[type='checkbox']").prop("checked", true);
		}
	})
	
//	$("#selectPath").click(function(){
//		service.openFolder({},function(json){
//			if(json.code == "200"){
//				if(!json.path){
//					return false
//				}
//				var abDir = json.path;
//				$("#h_ds_path").val(abDir);
//				var ls = abDir.substring(abDir.length,abDir.length-1);
//				if(ls == "/"){
//					abDir = abDir.substring(0,abDir.length-1);
//				}
//				$("#dsPath").val(abDir);
//			}else{
//				if(json.code == "900"){
//					return false;
//				}
//				plugin.msgtip({type: "e", msg: json.msg});
//			}
//		})
//	})
});

function selectFilePath(path){
	while(path.charAt(path.length - 1) == "\\" && path.charAt(path.length - 2) != ":"){
		path = path.substring(0,path.length-1)
	}
	$("#ab-ds-dir").val(path);
}

function getFont(treeId, node) {
    return node.font ? node.font : {};
}
function getPathTree(json,nodes){
	var j = 0;
	for(var i = 0;i<json.length; i++){
		var data = {};
		if(json[i].isParent){
			if(json[i].name.indexOf("\Desktop")!=-1){
				data.name = "桌面"
			}else{
				data.name = json[i].name;
			}
			data.path = json[i].absolutePath;
			data.isParent = json[i].isParent;
			data.iconSkin = "path";
			
			nodes[j] = data;
			j++;
		}	
	}
}

function pathClick(e,treeId, treeNode) {
	selectDsPath(treeNode.path);
}

var dsCB = function(data){
	var json = data;
	var ds = json.obj;
	
	if(ds.dsType == 0){
		$("#dbDiv").css("display","none");
	}else if(ds.dsType == 1){
		$("#folderDiv").css("display","none");
	}else if(ds.dsType == 2){
		$("#bsDiv").css("display","none");
		$("#dbDiv").css("display","none");
	}else{
		plugin.msgtip({type: "o", msg: "参数缺失！"});
//		window.history.go(-1);
	}

	if (ds.isOpenLocalBackup == 1) {
		$("#isOpenLocalBackup")[0].checked = true;
		$("#isOpenLocalBackup").siblings(".lab-check").addClass("check-true");
	}
	
	if (ds.isEncrypt == "0") {
		$("#isEncrypt")[0].checked = false;
		$("#isEncrypt").siblings(".lab-check").removeClass("check-true");
	}
	$("#isEncrypt").attr("disabled","disabled");
	$("#selectPath").attr("disabled","disabled");
	
	if (ds.dsSecurityRank == "1") {
		$("#dsNeedKey")[0].checked = true;
		$("#dsNeedKey").siblings(".lab-check").addClass("check-true");
	}else if (ds.dsSecurityRank == "2") {
		$("#dsNeedCode")[0].checked = true;
		$("#dsNeedCode").siblings(".lab-check").addClass("check-true");
	}else if (ds.dsSecurityRank == "3") {
		$("#dsNeedKey")[0].checked = true;
		$("#dsNeedCode")[0].checked = true;
		$("#dsNeedKey").siblings(".lab-check").addClass("check-true");
		$("#dsNeedCode").siblings(".lab-check").addClass("check-true");
	}

	$("#dsSecurityRank").val(ds.dsSecurityRank);
	$("#h_config_id").val(ds.configId);
	$("#h_backstrategy_id").val(ds.backupStrategyId);
	$('#dsPath').val(ds.root);
	$('#datetimepicker').val(getTimeStr(ds.backupTime));
	$('#dbUsername').val(ds.dbUsername);
	$('#dbPassword').val(ds.dbPassword);
	$('#dbType').val(ds.dbType);
	$('#dbName').val(ds.dbName);
	$('#dbHost').val(ds.dbHost);
	$('#dbPort').val(ds.dbPort);
	$('#unit').val(ds.backupPeriod);
	$('#period').val(ds.backupCycle);

}